package com.paireach.bw.activity;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.transition.Transition;
import android.transition.TransitionInflater;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.trace.TraceLocation;
import com.blankj.utilcode.utils.NetworkUtils;
import com.orhanobut.logger.Logger;
import com.paireach.bw.R;
import com.paireach.bw.application.MyApplication;
import com.paireach.bw.base.BaseActivity;
import com.paireach.bw.bean.LocationInfo;
import com.paireach.bw.bean.OrdersBean;
import com.paireach.bw.bean.ReturnInfo;
import com.paireach.bw.common.Constant;
import com.paireach.bw.event.AppEvent;
import com.paireach.bw.event.HttpErrorEvent;
import com.paireach.bw.event.HttpSuccessEvent;
import com.paireach.bw.http.RequestTag;
import com.paireach.bw.http.WayBillRequest;
import com.paireach.bw.interface2.LocateCallback;
import com.paireach.bw.utils.BDTraceUtil;
import com.paireach.bw.utils.GsonUtil;
import com.paireach.bw.utils.JsonParse;
import com.paireach.bw.utils.LocationService;
import com.paireach.bw.utils.LogUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import es.dmoral.toasty.Toasty;

/**
 * Created by ${cqc} on 2017/2/17.
 */

public class StartTransActivity extends BaseActivity implements View.OnClickListener {

    private static final String TAG = "StartTransActivity";
    private RecyclerView recyclerView;
    private Button btn;
    private MyRecyAdapter adapter;
    private Toolbar toolbar;
    private List<OrdersBean> orderList = new ArrayList<>();
    private String orderCode;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= 21) {
            getWindow().requestFeature(Window.FEATURE_CONTENT_TRANSITIONS);
            Transition slide_bottom = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_bottom);
            getWindow().setEnterTransition(slide_bottom);
        }
        setContentView(R.layout.activity_start_trans);
        orderCode = getIntent().getStringExtra("orderCode");
        findViews();
        initViews();

        showProgressDialog();
        new WayBillRequest().getOrderCodeDetail(phoneNumber, orderCode);
    }

    @Override
    public void httpSuccessEvent(HttpSuccessEvent event) {
        super.httpSuccessEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.GET_ORDER_CODE_DETAIL) {
            JsonParse.parseGetOrderCodeDetail(event.getJson());
        } else if (event.getRequestTag() == RequestTag.DRIVER_ACCEPT_ORDER) {
            jsonParse(event.getJson());
        }
    }

    private void jsonParse(String json) {
        ReturnInfo info = GsonUtil.jsonToBean(json, ReturnInfo.class);
        showToast(info.getMsg());
        if (info.getStatus() == 1) {
            finish();
            AppEvent event = new AppEvent();
            event.setTag("to_frag2");
            EventBus.getDefault().post(event);
        }
    }

    @Override
    public void httpErrorEvent(HttpErrorEvent event) {
        super.httpErrorEvent(event);
        dismissProgressDialog();
        if (event.getRequestTag() == RequestTag.GET_ORDER_CODE_DETAIL) {
            showWarning(event.getErrorMessage());
        } else if (event.getRequestTag() == RequestTag.DRIVER_ACCEPT_ORDER) {
            showWarning(event.getErrorMessage());
            finish();
        }
    }

    @Override
    public void applicationEvent(AppEvent event) {
        super.applicationEvent(event);
        if (event.getTag().equals("get_order_code_detail")) {
            if (event.getCode() == 1) {
                btn.setVisibility(View.VISIBLE);
                List<OrdersBean> orders = (List<OrdersBean>) event.getObj1();
                orderList.clear();
                orderList.addAll(orders);
                adapter.notifyDataSetChanged();
            } else {
                showWarning(event.getExtraInfo());
                btn.setVisibility(View.INVISIBLE);
            }
        }
    }


    private void findViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        btn = (Button) findViewById(R.id.btn);
    }


    private void initViews() {
        toolbar.setTitle("接收运单");
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.addItemDecoration(new DividerItemDecoration(context, LinearLayoutManager.VERTICAL));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        adapter = new MyRecyAdapter(orderList);
        recyclerView.setAdapter(adapter);

        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn:
                if (NetworkUtils.isConnected()) {
                    showProgressDialog();
                    BDTraceUtil.openTrace();
                    LocationInfo location = ((MyApplication) getApplication()).locationInfo;
                    new WayBillRequest().driverAcceptOrder(phoneNumber, orderCode, "", location.getLongitude() + "", "" + location.getLatitude(), driverNum);
                } else {
                    showToast("网络连接不可用，请稍后重试");
                }
                break;
        }
    }


    public class MyRecyAdapter extends RecyclerView.Adapter {


        private List<OrdersBean> list;

        public MyRecyAdapter(List<OrdersBean> list) {
            this.list = list;
        }


        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item1, parent, false);
            return new MyViewHolder(itemView);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, final int position) {
            MyViewHolder holder = (MyViewHolder) viewHolder;
            OrdersBean info = list.get(position);
            holder.tv_order_num.setText("交货单号：" + info.getSHPM_NUM());
            holder.tv_origin_name.setText("收货地名称：" + info.getFRM_SHPG_LOC_NAME());
            holder.tv_origin_address.setText("收货地址：" + info.getFRM_SHPG_ADDR());
            holder.tv_origin_time.setText("预约收货时间：" + info.getAPPOINTMENT_START_TIME());
            holder.tv_contacts.setText("联系人：" + info.getDRIVER_NAME());
            holder.tv_contacts_tel.setText("手机号：" + info.getDRIVER_MOBILE());
            String transport_code = info.getTRANSPORT_CODE();
            if ("KA".equals(transport_code)) {//KA
                holder.tv_order_style.setText("KA托盘");
            } else if ("BACK".equals(transport_code)) {//回瓶
                holder.tv_order_style.setText("回空");
            } else if ("COMMON".equals(transport_code)) {
                holder.tv_order_style.setText("常规");
            }
            holder.tv_order_state.setText(info.getSHPM_STATUS_NAME());
        }

        @Override
        public int getItemCount() {
            return list.size();
        }
    }

    private class MyViewHolder extends RecyclerView.ViewHolder {

        TextView tv_order_num;
        TextView tv_origin_name;
        TextView tv_origin_address;
        TextView tv_origin_time;
        TextView tv_contacts;
        TextView tv_contacts_tel;
        TextView tv_order_state;
        TextView tv_order_style;
        TextView tv_icon;

        public MyViewHolder(View itemView) {
            super(itemView);
            tv_icon = (TextView) itemView.findViewById(R.id.tv_icon);
            tv_order_num = (TextView) itemView.findViewById(R.id.tv_order_num);
            tv_origin_name = (TextView) itemView.findViewById(R.id.tv_origin_name);
            tv_origin_address = (TextView) itemView.findViewById(R.id.tv_origin_address);
            tv_origin_time = (TextView) itemView.findViewById(R.id.tv_origin_time);
            tv_contacts = (TextView) itemView.findViewById(R.id.tv_contacts);
            tv_contacts_tel = (TextView) itemView.findViewById(R.id.tv_contacts_tel);
            tv_order_style = (TextView) itemView.findViewById(R.id.tv_order_style);
            tv_order_state = (TextView) itemView.findViewById(R.id.tv_order_state);
        }
    }


    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，
     *
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                LogUtil.dLocation(location);
                new WayBillRequest().driverAcceptOrder(phoneNumber, orderCode, "", location.getLongitude() + "", "" + location.getLatitude(), driverNum);
            }
        }

        public void onConnectHotSpotMessage(String s, int i) {
        }
    };
}
